package com.doctor.controller.admin;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.doctor.common.JsonResult;
import com.doctor.controller.BaseController;
import com.doctor.entity.Department;
import com.doctor.service.DeparmentService;


@Controller
@RequestMapping("/admin/department")
public class DepartmentController extends BaseController{

  @Resource
  private DeparmentService departmentService;
  
  @GetMapping("/index")
  public String index() {
  		return "admin/department/index";
  }
  
  @GetMapping("/view")
  public String view(ModelMap map) {
      List<Department> list = departmentService.findAll();
      map.put("list", list);
      return "admin/department/view";
  }
  
  @PostMapping("/list")
  @ResponseBody
  public Page<Department> list() {
      PageRequest pageRequest = getPageRequest();
      Page<Department> page = departmentService.findAll(pageRequest);
      return page;
  }
  
  @GetMapping("/form")
  public String form(@RequestParam(required = false) Long id, ModelMap map) {
      if (id != null) {
      		Department Department = departmentService.findById(id);
          map.put("department", Department);
      }
      return "admin/department/form";
  }
  
  @PostMapping("/save")
  @ResponseBody
  public JsonResult save(Department Department) {
      try {
          if (Department != null) {
             	departmentService.saveOrUpdate(Department);
          }
      } catch (Exception e) {
          e.printStackTrace();
          return JsonResult.fail(e.getMessage());
      }
      return JsonResult.ok();
  }
	
	@PostMapping("/{id}/del")
  @ResponseBody
  public JsonResult delete(@PathVariable Long id) {
      try {
          departmentService.delete(id);
      } catch (Exception e) {
          e.printStackTrace();
          return JsonResult.fail(e.getMessage());
      }
      return JsonResult.ok();
  }
	
}
